package com.walnut.servlet;

import com.walnut.dao.UserDao;
import com.walnut.dao.impl.UserDaoImpl;
import com.walnut.pojo.User;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public Login() {
        super();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doGet(request, response);
        request.setCharacterEncoding("UTF-8");
        ServletContext context=request.getServletContext();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        UserDao userDao = new UserDaoImpl();
        try {
            if (!userDao.login(user)) {
                context.setAttribute("message", "用户名或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
            else {
                context.setAttribute("message", "登录成功");
                user=userDao.selectByName(username);
                String isAdmin=user.getIsAdmin().toString();
                context.setAttribute("isAdmin", isAdmin);
                context.setAttribute("loginer", username);
                request.getRequestDispatcher("/foodList").forward(request, response);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
